package com.hos.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

import java.io.IOException;
import java.util.UUID;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/20 9:07
 * @description:
 * @modified By:
 * @version:
 */
@Slf4j
public class OssUtils {
    private static final String ENDPOINT = "https://oss-cn-guangzhou.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "LTAI5tMXjzW4ZoV4FuZtQaYA";
    private static final String ACCESS_KEY_SECRET = "8XgZ79YqHmzpMe50EZS2cnsmKjN3dI";
    private static final String BUCKET_NAME = "hos-health";

    public static String ossUpload(MultipartFile multipartFile) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        //  上传的文件名称
        String fileName = "images/" + UUID.randomUUID().toString().replace("-", "")
                + multipartFile.getOriginalFilename();
        try {
            ossClient.putObject(BUCKET_NAME, fileName, multipartFile.getInputStream());
        } catch (OSSException | ClientException | IOException oe) {
            log.error(oe.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        //  文件访问路径
        return ENDPOINT.split("//")[0] + "//" + BUCKET_NAME + "." + ENDPOINT.split("//")[1] + "/" + fileName;
    }


    /**
     * oss文件删除
     *
     * @param pictureUrl 图片地址
     * @return 返回上传后的oss路径
     */
    public static void ossRemove(String pictureUrl) {
        String[] segments = pictureUrl.split("/");
        String filename = segments[segments.length - 1];


        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(BUCKET_NAME, filename);
        } catch (OSSException oe) {
            log.error(oe.getMessage());
        } catch (ClientException ce) {
            log.error(ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}